<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="许帅的博客" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    @Transactional注解浅谈 |  XuShuai&#39;blog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="XuShuai'blog" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      <canvas class="fireworks"></canvas>
      <style>
        .fireworks {
          position: fixed;
          left: 0;
          top: 0;
          z-index: 99999;
          pointer-events: none;
        }
      </style>
      
      
    <main class="content on">
      <section class="outer">
  <article
  id="spring-Transactional注解浅谈"
  class="article article-type-spring"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  @Transactional注解浅谈
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/07/28/Transactional%E6%B3%A8%E8%A7%A3%E6%B5%85%E8%B0%88/" class="article-date">
  <time datetime="2020-07-28T01:59:30.000Z" itemprop="datePublished">2020-07-28</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E6%A1%86%E6%9E%B6/">框架</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">3.7k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">15 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>引言： 在Spring中@Transactional提供一种控制事务管理的快捷手段，但是很多人都只是@Transactional简单使用，并未深入了解，其各个配置项的使用方法，本文将深入讲解各个配置项的使用。</p>
<h3 id="Transactional的定义"><a href="#Transactional的定义" class="headerlink" title="@Transactional的定义"></a>@Transactional的定义</h3><p>Spring中的@Transactional基于动态代理的机制，提供了一种透明的事务管理机制，方便快捷解决在开发中碰到的问题。在现实中，实际的问题往往比我们预期的要复杂很多，这就要求对@Transactional有深入的了解，以来应对复杂问题。</p>
<p>首先我们来看看@Transactional的源代码定义：</p>
<p>org.springframework.transaction.annotation.Transactional</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.METHOD, ElementType.TYPE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Inherited</span></span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Transactional &#123;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * A qualifier value for the specified transaction.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;May be used to determine the target transaction manager,</span></span><br><span class="line"><span class="comment">	 * matching the qualifier value (or the bean name) of a specific</span></span><br><span class="line"><span class="comment">	 * &#123;<span class="doctag">@link</span> org.springframework.transaction.PlatformTransactionManager&#125;</span></span><br><span class="line"><span class="comment">	 * bean definition.</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> ""</span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * The transaction propagation type.</span></span><br><span class="line"><span class="comment">	 * Defaults to &#123;<span class="doctag">@link</span> Propagation#REQUIRED&#125;.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior()</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function">Propagation <span class="title">propagation</span><span class="params">()</span> <span class="keyword">default</span> Propagation.REQUIRED</span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * The transaction isolation level.</span></span><br><span class="line"><span class="comment">	 * Defaults to &#123;<span class="doctag">@link</span> Isolation#DEFAULT&#125;.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLevel()</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function">Isolation <span class="title">isolation</span><span class="params">()</span> <span class="keyword">default</span> Isolation.DEFAULT</span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * The timeout for this transaction.</span></span><br><span class="line"><span class="comment">	 * Defaults to the default timeout of the underlying transaction system.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> org.springframework.transaction.interceptor.TransactionAttribute#getTimeout()</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">int</span> <span class="title">timeout</span><span class="params">()</span> <span class="keyword">default</span> TransactionDefinition.TIMEOUT_DEFAULT</span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * &#123;<span class="doctag">@code</span> true&#125; if the transaction is read-only.</span></span><br><span class="line"><span class="comment">	 * Defaults to &#123;<span class="doctag">@code</span> false&#125;.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;This just serves as a hint for the actual transaction subsystem;</span></span><br><span class="line"><span class="comment">	 * it will &lt;i&gt;not necessarily&lt;/i&gt; cause failure of write access attempts.</span></span><br><span class="line"><span class="comment">	 * A transaction manager which cannot interpret the read-only hint will</span></span><br><span class="line"><span class="comment">	 * &lt;i&gt;not&lt;/i&gt; throw an exception when asked for a read-only transaction.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">boolean</span> <span class="title">readOnly</span><span class="params">()</span> <span class="keyword">default</span> <span class="keyword">false</span></span>;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Defines zero (0) or more exception &#123;<span class="doctag">@link</span> Class classes&#125;, which must be a</span></span><br><span class="line"><span class="comment">	 * subclass of &#123;<span class="doctag">@link</span> Throwable&#125;, indicating which exception types must cause</span></span><br><span class="line"><span class="comment">	 * a transaction rollback.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;This is the preferred way to construct a rollback rule, matching the</span></span><br><span class="line"><span class="comment">	 * exception class and subclasses.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;Similar to &#123;<span class="doctag">@link</span> org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)&#125;</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	Class&lt;? extends Throwable&gt;[] rollbackFor() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Defines zero (0) or more exception names (for exceptions which must be a</span></span><br><span class="line"><span class="comment">	 * subclass of &#123;<span class="doctag">@link</span> Throwable&#125;), indicating which exception types must cause</span></span><br><span class="line"><span class="comment">	 * a transaction rollback.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;This can be a substring, with no wildcard support at present.</span></span><br><span class="line"><span class="comment">	 * A value of "ServletException" would match</span></span><br><span class="line"><span class="comment">	 * &#123;<span class="doctag">@link</span> javax.servlet.ServletException&#125; and subclasses, for example.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;&lt;b&gt;NB: &lt;/b&gt;Consider carefully how specific the pattern is, and whether</span></span><br><span class="line"><span class="comment">	 * to include package information (which isn't mandatory). For example,</span></span><br><span class="line"><span class="comment">	 * "Exception" will match nearly anything, and will probably hide other rules.</span></span><br><span class="line"><span class="comment">	 * "java.lang.Exception" would be correct if "Exception" was meant to define</span></span><br><span class="line"><span class="comment">	 * a rule for all checked exceptions. With more unusual &#123;<span class="doctag">@link</span> Exception&#125;</span></span><br><span class="line"><span class="comment">	 * names such as "BaseBusinessException" there is no need to use a FQN.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;Similar to &#123;<span class="doctag">@link</span> org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)&#125;</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	String[] rollbackForClassName() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Defines zero (0) or more exception &#123;<span class="doctag">@link</span> Class Classes&#125;, which must be a</span></span><br><span class="line"><span class="comment">	 * subclass of &#123;<span class="doctag">@link</span> Throwable&#125;, indicating which exception types must &lt;b&gt;not&lt;/b&gt;</span></span><br><span class="line"><span class="comment">	 * cause a transaction rollback.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;This is the preferred way to construct a rollback rule, matching the</span></span><br><span class="line"><span class="comment">	 * exception class and subclasses.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;Similar to &#123;<span class="doctag">@link</span> org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)&#125;</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	Class&lt;? extends Throwable&gt;[] noRollbackFor() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Defines zero (0) or more exception names (for exceptions which must be a</span></span><br><span class="line"><span class="comment">	 * subclass of &#123;<span class="doctag">@link</span> Throwable&#125;) indicating which exception types must &lt;b&gt;not&lt;/b&gt;</span></span><br><span class="line"><span class="comment">	 * cause a transaction rollback.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;See the description of &#123;<span class="doctag">@link</span> #rollbackForClassName()&#125; for more info on how</span></span><br><span class="line"><span class="comment">	 * the specified names are treated.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;Similar to &#123;<span class="doctag">@link</span> org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)&#125;</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	String[] noRollbackForClassName() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>基于源代码，我们可以发现在@Transactional中，原来有这么多的属性可以进行配置，从而达到复杂应用控制的目的。具体各个属性的用法和作用，将在下面逐一进行讲解和说明。</p>
<h3 id="Transactional注解中常用参数说明"><a href="#Transactional注解中常用参数说明" class="headerlink" title="@Transactional注解中常用参数说明"></a>@Transactional注解中常用参数说明</h3><table>
<thead>
<tr>
<th>参数名称</th>
<th>功能描述</th>
</tr>
</thead>
<tbody><tr>
<td>readOnly</td>
<td>该属性用于设置当前事务是否为只读事务，设置为true表示只读，false则表示可读写，默认值为false。例如：@Transactional(readOnly=true)</td>
</tr>
<tr>
<td>rollbackFor</td>
<td>该属性用于设置需要进行回滚的异常类数组，当方法中抛出指定异常数组中的异常时，则进行事务回滚。例如：指定单一异常类：@Transactional(rollbackFor=RuntimeException.class)指定多个异常类：@Transactional(rollbackFor={RuntimeException.class, Exception.class})</td>
</tr>
<tr>
<td>rollbackForClassName</td>
<td>该属性用于设置需要进行回滚的异常类名称数组，当方法中抛出指定异常名称数组中的异常时，则进行事务回滚。例如：指定单一异常类名称：@Transactional(rollbackForClassName=”RuntimeException”)指定多个异常类名称：@Transactional(rollbackForClassName={“RuntimeException”,”Exception”})</td>
</tr>
<tr>
<td>noRollbackFor</td>
<td>该属性用于设置不需要进行回滚的异常类数组，当方法中抛出指定异常数组中的异常时，不进行事务回滚。例如：指定单一异常类：@Transactional(noRollbackFor=RuntimeException.class)指定多个异常类：@Transactional(noRollbackFor={RuntimeException.class, Exception.class})</td>
</tr>
<tr>
<td>noRollbackForClassName</td>
<td>该属性用于设置不需要进行回滚的异常类名称数组，当方法中抛出指定异常名称数组中的异常时，不进行事务回滚。例如：指定单一异常类名称：@Transactional(noRollbackForClassName=”RuntimeException”)指定多个异常类名称：@Transactional(noRollbackForClassName={“RuntimeException”,”Exception”})</td>
</tr>
<tr>
<td>propagation</td>
<td>该属性用于设置事务的传播行为，具体取值可参考表6-7。例如：@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)</td>
</tr>
<tr>
<td>isolation</td>
<td>该属性用于设置底层数据库的事务隔离级别，事务隔离级别用于处理多事务并发的情况，通常使用数据库的默认隔离级别即可，基本不需要进行设置</td>
</tr>
<tr>
<td>timeout</td>
<td>该属性用于设置事务的超时秒数，默认值为-1表示永不超时</td>
</tr>
<tr>
<td>-</td>
<td></td>
</tr>
<tr>
<td><strong>事物传播行为介绍:</strong></td>
<td></td>
</tr>
</tbody></table>
<pre><code>@Transactional(propagation=Propagation.REQUIRED) ：如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)

@Transactional(propagation=Propagation.NOT_SUPPORTED) ：容器不为这个方法开启事务

@Transactional(propagation=Propagation.REQUIRES_NEW) ：不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务

@Transactional(propagation=Propagation.MANDATORY) ：必须在一个已有的事务中执行,否则抛出异常

@Transactional(propagation=Propagation.NEVER) ：必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)

@Transactional(propagation=Propagation.SUPPORTS) ：如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.

@Transactional(propagation=Propagation.NESTED) ： 如果当前存在事务，则在嵌套事务内执行。如果当前没有事务，则进行与PROPAGATION_REQUIRED类似的操作。 

前六个策略类似于EJB CMT，第七个（PROPAGATION_NESTED）是Spring所提供的一个特殊变量。 它要求事务管理器或者使用JDBC 3.0 Savepoint API提供嵌套事务行为（如Spring的DataSourceTransactionManager） </code></pre><ul>
<li><strong>事物超时设置:</strong></li>
</ul>
<p>　　@Transactional(timeout=30) //默认是30秒</p>
<ul>
<li></li>
</ul>
<p><strong>事务隔离级别:</strong></p>
<p>　　@Transactional(isolation = Isolation.READ_UNCOMMITTED)：读取未提交数据(会出现脏读, 不可重复读) 基本不使用</p>
<p>　　@Transactional(isolation = Isolation.READ_COMMITTED)：读取已提交数据(会出现不可重复读和幻读)</p>
<p>　　@Transactional(isolation = Isolation.REPEATABLE_READ)：可重复读(会出现幻读)</p>
<p>　　@Transactional(isolation = Isolation.SERIALIZABLE)：串行化</p>
<p>   MYSQL: 默认为REPEATABLE_READ级别</p>
<p>   SQLSERVER: 默认为READ_COMMITTED</p>
<p>   脏读 : 一个事务读取到另一事务未提交的更新数据</p>
<p>  不可重复读 : 在同一事务中, 多次读取同一数据返回的结果有所不同, 换句话说,<br>  后续读取可以读到另一事务已提交的更新数据. </p>
<p>  可重复读:在同一事务中多次<br>    读取数据时, 能够保证所读数据一样, 也就是后续读取不能读到另一事务已提交的更新数据</p>
<p>  幻读 : 一个事务读到另一个事务已提交的insert数据</p>
<p><strong>注意的几点:</strong></p>
<p>1、@Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能.</p>
<p>2、用 spring 事务管理器,由spring来负责数据库的打开,提交,回滚.默认遇到运行期例外(throw new RuntimeException(“注释”);)会回滚，即遇到不受检查（unchecked）的例外时回滚；而遇到需要捕获的例外(throw new Exception(“注释”);)不会回滚,即遇到受检查的例外（就是非运行时抛出的异常，编译器会检查到的异常叫受检查例外或说受检查异常）时，需我们指定方式来让事务回滚要想所有异常都回滚,要加上 @Transactional( rollbackFor={Exception.class,其它异常}) .如果让unchecked例外不回滚： @Transactional(notRollbackFor=RunTimeException.class)<br>如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span> <span class="meta">@Transactional</span>(rollbackFor=Exception<span class="class">.<span class="keyword">class</span>) //指定回滚,遇到异常<span class="title">Exception</span>时回滚</span></span><br><span class="line"><span class="class">2 <span class="title">public</span> <span class="title">void</span> <span class="title">methodName</span>() </span>&#123;</span><br><span class="line"><span class="number">3</span> 　　　<span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"注释"</span>);</span><br><span class="line"><span class="number">4</span> &#125;</span><br><span class="line">5 @Transactional(noRollbackFor=Exception.class)//指定不回滚,遇到运行期例外(throw new RuntimeException("注释");)会回滚</span><br><span class="line"><span class="number">6</span> <span class="function"><span class="keyword">public</span> ItimDaoImpl <span class="title">getItemDaoImpl</span><span class="params">()</span> </span>&#123;</span><br><span class="line"><span class="number">7</span> 　　　<span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"注释"</span>);</span><br><span class="line"><span class="number">8</span> &#125;</span><br></pre></td></tr></table></figure>
<p>3、@Transactional 注解应该只被应用到 public 可见度的方法上。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解，它也不会报错， 但是这个被注解的方法将不会展示已配置的事务设置。</p>
<p>　　4、@Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。然而，请注意仅仅 @Transactional 注解的出现不足于开启事务行为，它仅仅 是一种元数据，能够被可以识别 @Transactional 注解和上述的配置适当的具有事务行为的beans所使用。上面的例子中，其实正是 元素的出现 开启 了事务行为。</p>
<p>　　5、Spring团队的建议是你在具体的类（或类的方法）上使用 @Transactional 注解，而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解，但是这将只能当你设置了基于接口的代理时它才生效。因为注解是不能继承的，这就意味着如果你正在使用基于类的代理时，那么事务的设置将不能被基于类的代理所识别，而且对象也将不会被事务代理所包装（将被确认为严重的）。因此，请接受Spring团队的建议并且在具体的类上使用 @Transactional 注解。</p>
<h3 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h3><h4 id="例子讲解以上七中事务传播机制"><a href="#例子讲解以上七中事务传播机制" class="headerlink" title="例子讲解以上七中事务传播机制"></a>例子讲解以上七中事务传播机制</h4><p>自己写的一个测试</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RunWith</span>(SpringRunner<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">@<span class="title">SpringBootTest</span>(<span class="title">classes</span> </span>= Application<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">UserBaseInfoControllerTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserBaseInfoService userBaseInfoService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="meta">@Transactional</span>(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">void</span> <span class="title">testOne</span>() </span>&#123;</span><br><span class="line">        UserBaseInfo userBaseInfo = <span class="keyword">new</span> UserBaseInfo();</span><br><span class="line">        userBaseInfo.setId(<span class="number">3</span>);</span><br><span class="line">        userBaseInfo.setUserName(<span class="string">"xu2"</span>);</span><br><span class="line">        userBaseInfo.setPassWord(<span class="string">"111111"</span>);</span><br><span class="line">        userBaseInfoService.update(userBaseInfo);</span><br><span class="line">        userBaseInfo.setUserName(<span class="string">"xu1"</span>);</span><br><span class="line">        userBaseInfo.setPassWord(<span class="string">"1111111"</span>);</span><br><span class="line">        userBaseInfoService.save(userBaseInfo);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserBaseInfoServiceImpl</span> <span class="keyword">extends</span> <span class="title">AbstractService</span>&lt;<span class="title">UserBaseInfo</span>&gt; <span class="keyword">implements</span> <span class="title">UserBaseInfoService</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> UserBaseInfoMapper userBaseInfoMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(UserBaseInfo userBaseInfo)</span> </span>&#123;</span><br><span class="line">        mapper.insertSelective(userBaseInfo);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation=Propagation.MANDATORY,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation=Propagation.NESTED,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation=Propagation.NEVER,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation=Propagation.NOT_SUPPORTED,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="comment">//@Transactional(propagation=Propagation.SUPPORTS,rollbackFor = RuntimeException.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(UserBaseInfo userBaseInfo)</span> </span>&#123;</span><br><span class="line">        mapper.updateByPrimaryKeySelective(userBaseInfo);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>假设有类A的方法methodB(),有类B的方法methodB().</p>
<p>1)     PROPAGATION_REQUIRED</p>
<p>如果B的方法methodB()的事务传播特性是propagation_required，那么如下图</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_ccf3aea9741cd3ccd53883b11f02eb0f.png" alt="image.png"></p>
<p>A.methodA()调用B的methodB()方法，那么如果A的方法包含事务，则B的方法则不从新开启事务，</p>
<p>1、  如果B的methodB()抛出异常，A的methodB()没有捕获，则A和B的事务都会回滚；</p>
<p>2、   如果B的methodB()运行期间异常会导致B的methodB()的回滚，A如果捕获了异常，并正常提交事务，则会发生Transaction rolled back because it has been marked as rollback-only的异常。</p>
<p>3、  如果A的methodA()运行期间异常，则A和B的Method的事务都会被回滚</p>
<p>2)     PROPAGATION_SUPPORTS</p>
<p>如果B的方法methodB()的事务传播特性是propagation_supports,么如下图</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_473e10169a50977aa7a514e0cf2e2932.png" alt="image.png"></p>
<p>A.methodA()调用B的methodB()方法，那么如果A的方法包含事务，则B运行在此事务环境中，如果A的方法不包含事务，则B运行在非事务环境；</p>
<p>1、如果A没有事务，则A和B的运行出现异常都不会回滚。</p>
<p>2、如果A有事务，A的method方法执行抛出异常，B.methodB和A.methodA都会回滚。</p>
<p>3、如果A有事务，B.method抛出异常，B.methodB和A.methodA都会回滚，如果A捕获了B.method抛出的异常，则会出现异常Transactionrolled back because it has been marked as rollback-only。</p>
<p>3)     PROPAGATION_MANDATORY</p>
<p>表示当前方法必须在一个事务中运行，如果没有事务，将抛出异常，如下图调用关系：</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_6b9f8a70d416ee7e001123af67be32dc.png" alt="image.png"></p>
<p>B.methodB()事务传播特性定义为:PROPAGATION_MANDATORY</p>
<p>1、如果A的methoda()方法没有事务运行环境，则B的methodB()执行的时候会报如下异常：No existingtransaction found for transaction marked with propagation ‘mandatory’</p>
<p>2、如果A的Methoda()方法有事务并且执行过程中抛出异常，则A.methoda（）和B.methodb（）执行的操作被回滚；</p>
<p>3、如果A的methoda()方法有事务，则B.methodB()抛出异常时，A的methoda()和B.methodB()都会被回滚；如果A捕获了B.method抛出的异常，则会出现异常Transaction rolled back because ithas been marked as rollback-only</p>
<p>4)     PROPAGATION_NESTED</p>
<p>如有一下方法调用关系，如图：</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_ed661526a000685a461e9ae05cb91113.png" alt="image.png"></p>
<p>B的methodB()定义的事务为PROPAGATION_NESTED；</p>
<p>1、        如果A的MethodA()不存在事务，则B的methodB()运行在一个新的事务中，B.method()抛出的异常，B.methodB()回滚,但A.methodA()不回滚；如果A.methoda()抛出异常，则A.methodA()和B.methodB()操作不回。</p>
<p>2、        如果A的methodA()存在事务，则A的methoda()抛出异常，则A的methoda()和B的Methodb()都会被回滚；</p>
<p>3、        如果A的MethodA()存在事务，则B的methodB()抛出异常，B.methodB()回滚，如果A不捕获异常，则A.methodA()和B.methodB()都会回滚，如果A捕获异常，则B.methodB()回滚,A不回滚；</p>
<p>5）PROPAGATION_NEVER</p>
<p>表示事务传播特性定义为PROPAGATION_NEVER的方法不应该运行在一个事务环境中</p>
<p>有如下调用关系：</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_8ec3ee0c3d2e92073af6945ad98b520f.png" alt="image.png"></p>
<p>如果B.methodB()的事务传播特性被定义为PROPAGATION_NEVER，则如果A.methodA()方法存在事务，则会出现异常Existingtransaction found for transaction marked with propagation ‘never’。</p>
<p>6）PROPAGATION_REQUIRES_NEW</p>
<p>   表示事务传播特性定义为PROPAGATION_REQUIRES_NEW的方法需要运行在一个新的事务中。</p>
<p>如有以下调用关系：B.methodB()事务传播特性为PROPAGATION_REQUIRES_NEW.</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_60d9094e0ad958b492104adf30ad9d09.png" alt="image.png"></p>
<p>1、        如果A存在事务，A.methodA()抛出异常，A.methodA()的事务被回滚，但B.methodB()事务不受影响；如果B.methodB()抛出异常，A不捕获的话，A.methodA()和B.methodB()的事务都会被回滚。如果A捕获的话，A.methodA()的事务不受影响但B.methodB()的事务回滚。</p>
<p>7) PROPAGATION_NOT_SUPPORTED</p>
<p>表示该方法不应该在一个事务中运行。如果有一个事务正在运行，他将在运行期被挂起，直到这个事务提交或者回滚才恢复执行。</p>
<p>如有一下调用关系图：</p>
<p><img src="http://192.168.5.79:4000/static/upload/20190102/upload_34a234baa28a8a1f10375297455ef3d3.png" alt="image.png"></p>
<p>如果B.methodB()方法传播特性被定义为：PROPAGATION_NOT_SUPPORTED。</p>
<p>1、        如果A.methodA()存在事务，如果B.methodB()抛出异常，A.methodA()不捕获的话，A.methodA()的事务被回滚，而B.methodB()出现异常前数据库操作不受影响。如果A.methodA()捕获的话，则A.methodA()的事务不受影响，B.methodB()异常抛出前的数据操作不受影响。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://yoursite.com/2020/07/28/Transactional%E6%B3%A8%E8%A7%A3%E6%B5%85%E8%B0%88/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Transactional/" rel="tag">Transactional</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/spring/" rel="tag">spring</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/07/28/%E7%AC%AC%E4%B8%80%E7%AF%87%E6%97%85%E8%A1%8C%E5%8D%9A%E5%AE%A2/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            第一篇旅行博客
          
        </div>
      </a>
    
    
      <a href="/2020/07/28/Nginx%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86%E5%92%8C%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Nginx反向代理和负载均衡</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "i1EbtBg59Bh3RK2oHupK7DpQ-gzGzoHsz",
    app_key: "hhxN6zertD64fj3M4CMoW9u8",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020
        <i class="ri-heart-fill heart_icon"></i> shuai xu
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="XuShuai&#39;blog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/photos">相册</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="https://zaishanhaizhijiandechengxuyuan.lofter.com" target="_blank" rel="noopener">生活</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->


    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css">
        <script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"></script>
        
    


<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script>

<script src="/js/clickBoom1.js"></script>


<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=22707008&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
  </div>
</body>

</html>